/**
 * @description vue的混入功能
 * @author 印明帝
 */
import BlogList from 'components/common/BlogList'
import LoadMore from 'components/common/LoadMore'
import {
  getFirstBlog,
  loadMoreBlog
} from 'api/blog'

import { upload } from 'api/utils'

const fileMixin = {
  methods: {
    /**
     * 获取上传的图片文件
     * @method uploadFile
     */
    async uploadFile (e) {
      let file = e.target.files[0]
      let result = await upload(file)
      if (result.errno !== 0) {
        alert(result.message)
        return null
      }
      // this.picture = result.data
      return result
    }
  }
}

// 博客列表混入
const bolgListMixin = {
  components: {
    BlogList,
    LoadMore
  },
  data () {
    return {
      isMe: false,
      id: 0,
      index: 0,
      bolgData: {},
      blogListData: []
    }
  },
  computed: {
    // 是否显示加载更多
    isLoadMore () {
      if (this.blogListData) {
        return this.bolgData.count > this.blogListData.length
      }
      return false
    }
  },
  methods: {
    /**
     * 获取第一页博客数据
     * @methods getBlogListData
     */
    async getBlogListData () {
      let routerName = this.$route.name
      let id = this.$route.params.id
      // 如果路由不是广场页面就携带id值
      if (routerName !== 'square') {
        // 如果不是指定id，默认获取当前登录用户的id
        if (!id) {
          id = 'currentId'
          this.isMe = true
        } else {
          this.isMe = false
        }
      }
      this.id = id
      let result = await getFirstBlog(id)
      if (result.errno === 0) {
        this.bolgData = result.data
        this.blogListData = this.bolgData.blogs
      } else {
        alert(result.message)
      }
    },
    /**
     * 获取后续的博客数据
     * @methods getMoreBlog
     */
    async getMoreBlog () {
      this.index++
      // 获取后续
      let result = await loadMoreBlog(this.id, this.index)
      // 是否获取到成功数据
      if (result.errno === 0) {
        this.blogListData.push(...result.data.blogs)
      } else {
        this.index--
        alert(result.message)
      }
    }
  },
  created () {
    this.getBlogListData()
  },
  activated () {
    this.getBlogListData()
  }
}

export {
  fileMixin,
  bolgListMixin
}
